﻿using System;
using System.Linq;
using System.Web.UI.WebControls;
using Service;

namespace ECommerce.Controls
{
	public partial class OrderingShipping : BaseUserControl
	{
		private IAddressService _AddressService;
		private ICountryService _CountryService;
		private IStateProvinceService _StateProvinceService;
		private IShippingMethodService _ShippingMethodService;

		public int TheSelectedAddressStateProvinceID
		{
			get
			{
				var obj = ViewState["TheSelectedAddressStateProvinceID"];

				if (obj != null)
				{
					var addressID = (int)ViewState["TheSelectedAddressStateProvinceID"];

					return addressID;
				}

				return 0;
			}
			set
			{
				ViewState["TheSelectedAddressStateProvinceID"] = value;
			}
		}

		public int SelecrtedAddressID
		{
			get
			{
				int theResult = -1;

				if (GridAddress.SelectedRow != null)
				{
					object obj = GridAddress.DataKeys[GridAddress.SelectedIndex]["AddressId"];
					if (obj != null)
					{
						int theSelectedAddressID = (int)obj;
						if (theSelectedAddressID > 0)
						{
							return theSelectedAddressID;
						}
					}
				}

				return theResult;
			}
		}

		public int SeletedShippingMethodID
		{
			get
			{
				int theResult = -1;

				if (RadioListShippingMethods.SelectedItem != null)
				{
					int.TryParse(RadioListShippingMethods.SelectedValue, out theResult);
				}

				return theResult;
			}
		}

		public bool CheckShippingAddressHasSelected()
		{
			var result = RadioListShippingMethods.SelectedItem != null;

			if (!result)
			{
				RadioListShippingMethods.Focus();
			}

			return result;
		}

		protected void Page_Load(object sender, EventArgs e)
		{
		}

		protected void Page_PreRender(object sender, EventArgs e)
		{
			HyperLinkAlterAddress.Text = GetLocalResourceString("OrderingShippingAddress.AlterAddressLink.Text") + "/" + GetLocalResourceString("AddressManage.AddNewAddressLink");
			HyperLinkAlterAddress.NavigateUrl = "~/Customer/AddressManage.aspx";

			this.LSelectShippingAddress.Text = GetLocalResourceString("OrderingShippingAddress.SelectShippingAddress");
			this.LSelectShippingMethodTitle.Text = GetLocalResourceString("OrderingShippingAddress.SelectShippingMethod.Title");

			BindMyAddress();

			BindShippingMethods();
		}

		protected void GridAddress_RowCommand(object source, GridViewCommandEventArgs e)
		{
			if (SiteContext.Current == null)
			{
				Server.Transfer("~/HomePage.aspx");
			}

			if (e.CommandName.ToLower().Equals("select"))
			{
				int theAddressID = 0;

				if (int.TryParse(e.CommandArgument.ToString(), out theAddressID))
				{
					if (_AddressService == null)
					{
						_AddressService = new AddressService();
					}
					var userID = (Guid)SiteContext.Current.User.ProviderUserKey;
					var theAddress = (from add in _AddressService.GetTheUserAddresses(userID)
									  where add.AddressId.Equals(theAddressID)
									  select add).FirstOrDefault();

					if (theAddress != null)
					{
						TheSelectedAddressStateProvinceID = theAddress.StateProvinceID;
						SetShippingMethodsTransportCosts();
					}
				}
			}
		}

		protected void GridAddress_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.DataItem != null)
			{
				var LinkButtonSelect = e.Row.FindControl("LinkButtonSelect") as LinkButton;

				LinkButtonSelect.Text = GetLocalResourceString("ECommerce.SelectButton.Text");
			}
		}

		private void SetShippingMethodsTransportCosts()
		{
			if (TheSelectedAddressStateProvinceID > 0)
			{
				if (_ShippingMethodService == null)
				{
					_ShippingMethodService = new ShippingMethodService();
				}

				var data = _ShippingMethodService.GetShippingByStateAndProvinceByProvince(TheSelectedAddressStateProvinceID);

				if (data != null && data.Count > 0)
				{
					//var shippingMethodByProvinceCosts = data.ToList();

					//if (shippingMethodByProvinceCosts.Count > 0)
					//{
					foreach (ListItem item in RadioListShippingMethods.Items)
					{
						var shippingMethodID = int.Parse(item.Value);

						var thecost = data.ToList().Find(m => m.ShippingMethodID.Equals(shippingMethodID));

						if (thecost != null)
						{
							if (item.Text.Contains('/'))
							{
								item.Text = item.Text.Split('/')[0] + "/(" + thecost.TransportCosts.ToString("c2") + ")";
							}
							else
							{
								item.Text += "/(" + thecost.TransportCosts.ToString("c2") + ")";
							}
						}
					}
					//}
				}
			}
		}

		private void BindMyAddress()
		{
			if (SiteContext.Current == null)
			{
				Server.Transfer("~/HomePage.aspx");
			}

			var user = SiteContext.Current.User;

			if (user != null)
			{
				if (_AddressService == null)
				{
					_AddressService = new AddressService();
				}
				if (_CountryService == null)
				{
					_CountryService = new CountryService();
				}
				if (_StateProvinceService == null)
				{
					_StateProvinceService = new StateProvinceService();
				}

				var userID = (Guid)user.ProviderUserKey;

				var addressData = _AddressService.GetTheUserAddresses(userID);

				if (addressData != null)
				{
					var addresses = (from address in addressData
									 join country in _CountryService.GetAllCountry() on address.CountryID equals country.CountryID
									 join state in _StateProvinceService.GetAllStateProvince() on address.StateProvinceID equals state.StateProvinceID
									 join city in _StateProvinceService.GetAllCity() on address.CityID equals city.CityID into acsc
									 from fulladdress in acsc.DefaultIfEmpty()
									 select new
									 {
										 Address1 = address.Address1,
										 Address2 = address.Address2,
										 AddressId = address.AddressId,
										 StateAndCity = country.Name + " " + state.Name + " " + ((fulladdress == null) ? string.Empty : fulladdress.CityName),
										 Company = address.Company,
										 UserName = address.FirstName + address.LastName,
										 MobileNumber = address.MobileNumber,
										 PhoneNumber = address.PhoneNumber,
										 ZipPostalCode = address.ZipPostalCode
									 });

					GridAddress.DataSource = addresses;
					GridAddress.DataBind();
				}
			}
		}

		private void BindShippingMethods()
		{
			if (_ShippingMethodService == null)
			{
				_ShippingMethodService = new ShippingMethodService();
			}

			var shippingMethods = _ShippingMethodService.GetAllShippingMethod();

			if (shippingMethods != null && shippingMethods.Count > 0)
			{
				foreach (var shippingMethodItem in shippingMethods)
				{
					ListItem li = new ListItem(GetLocalResourceString("ShippingMethod." + shippingMethodItem.Name), shippingMethodItem.ShippingMethodID.ToString());

					RadioListShippingMethods.Items.Add(li);
				}
			}
		}
	}
}
